package com.iflytek.ci.cpms.controller;

import com.alibaba.druid.util.StringUtils;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.iflytek.ci.common.support.DateEditor;
import com.iflytek.ci.cpms.domain.Milestone;
import com.iflytek.ci.cpms.domain.Project;
import com.iflytek.ci.cpms.service.MilestoneService;
import com.iflytek.ci.cpms.service.ProjectService;
import com.iflytek.ci.cums.domain.Account;
import com.iflytek.ci.cums.service.AccountService;
import com.iflytek.ci.cums.service.impl.ShiroDbRealm;
import com.iflytek.ci.main.controller.BaseController;
import com.iflytek.ci.main.dto.CommboValue;
import com.iflytek.ci.main.dto.Macro;
import com.iflytek.ci.qams.domain.Issue;
import com.iflytek.ci.qams.domain.Priopity;
import com.iflytek.ci.qams.service.IssueService;
import com.iflytek.ci.qams.service.LabelService;
import com.iflytek.ci.qams.service.PriopityService;
import com.iflytek.ci.qams.service.TypeService;
import com.iflytek.framework.mapper.JsonMapper;
import com.iflytek.framework.pagination.PaginationCriteria;
import com.iflytek.framework.pagination.PaginationResult;
import com.iflytek.framework.web.messages.AjaxMessage;
import com.iflytek.framework.web.mvc.PaginationParam;
import org.apache.shiro.SecurityUtils;
import org.dozer.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 里程碑维护管理控制器.
 * </p>
 *
 * @author mdzhang
 * @version 2.0
 * @since JDK 1.5
 */
@Controller
@RequestMapping("project/milestone/**")
public class MilestoneController extends BaseController {
	/** 序列号 */
	private static final long serialVersionUID = 5767889157435108850L;
	/** 里程碑服务 */
	@Autowired
	public MilestoneService milestoneService;
	/** 项目服务 */
	@Autowired
	public ProjectService projectService;
	/** 映射 */
	@Autowired
	public Mapper mapper;
	/** 账户服务 */
	@Autowired
	public AccountService accountService;
	/** 反馈服务 */
	@Autowired
	private IssueService issueService;
	/** 类型服务 */
	@Autowired
	private TypeService typeService;
	/** 标签服务 */
	@Autowired
	private LabelService labelService;
	/** 优先级服务 */
	@Autowired
	private PriopityService priopityService;

	/**
	 * 跳转到milestone管理界面
	 *
	 * @return list界面
	 */
	@RequestMapping(value = "list/{code}", method = RequestMethod.GET)
	public String list(@PathVariable("code") String code, Model model) {
//		Project project = null;
		ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) SecurityUtils.getSubject().getPrincipal();
//		if (projectId == 0) {
//			project = new Project();
//		} else {
//			project = projectService.fromId(projectId);
//		}
		Project project = projectService.fromKey(code);
		String role = "User";
		String Leader = "Not";
		if (SecurityUtils.getSubject().hasRole("Admin")) {
			role = "Admin";
		} else if (SecurityUtils.getSubject().hasRole("Leader")) {
			role = "Leader";
		}
		if (StringUtils.equals(project.getDev_leader(), shiroUser.getLogin()) || StringUtils.equals(project.getLead(), shiroUser.getLogin())) {
			Leader = "Leader";
		}
		model.addAttribute("account_json", JsonMapper.nonDefaultMapper().toJson(accountService.get_all()));
		model.addAttribute("project", project);
		model.addAttribute("login_json", JsonMapper.nonDefaultMapper()
				.toJson(shiroUser.getId()));
		model.addAttribute("role_json", JsonMapper.nonDefaultMapper()
				.toJson(role));
		model.addAttribute("Leader_json", JsonMapper.nonDefaultMapper()
				.toJson(Leader));
		return "project/milestone/list";
	}

	@RequestMapping("list.json")
	@ResponseBody
	public PaginationResult<Milestone> all_milestone(
			@PaginationParam(required = false) PaginationCriteria criteria,
			@RequestParam(value = "project_id", required = false) String p_id, Model model) {
		return milestoneService.get_milestone(criteria, Long.valueOf(p_id));

	}

	/** 里程碑报告界面 */
	@RequestMapping("report")
	public String getReport(Model model) {
		model.addAttribute("project", projectService.fromId(1));
		return "project/milestone/reporter";
	}

	/**
	 * 跳转到里程碑的编辑或者新增界面,id为0表示新增，否则为编辑
	 *
	 * @param mid   里程碑id
	 * @param pid   项目id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "edit/{mid}/{pid}", method = RequestMethod.GET)
	public String edit(@PathVariable("mid") int mid,
					   @PathVariable("pid") int pid, Model model) {
		Milestone milestone;
		Project project = null;
		if (mid == 0) {
			milestone = new Milestone();
		} else {
			milestone = milestoneService.get_milestone_id(mid);
		}
		if (pid == 0) {
			project = new Project();
		} else {
			project = projectService.fromId(pid);
		}
		// ProjectInformation
		// projectinfo=projectService.getProjectInformation(project_id);
		model.addAttribute("milestone", milestone);
		model.addAttribute("project", project);

		// model.addAttribute("projectinfo",projectinfo);
		return "project/milestone/edit";
	}

	/**
	 * 保存
	 *
	 * @param milestone
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "save")
	public AjaxMessage save(@Valid Milestone milestone, BindingResult result) {
		if (result.hasErrors()) {
			return ajax_error("数据校验错误", result.getAllErrors());
		}
		if (milestone.getId() == 0) {
			milestoneService.add_new(milestone);

		} else {
			milestoneService.update_milestone(milestone);
		}
		return ajax_info("保存成功");
	}

	/**
	 * 删除1个或者多个里程碑信息
	 *
	 * @param ids 里程碑，以逗号分割
	 * @return 是否成功
	 */
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxMessage delete(String ids) {
		if (Strings.isNullOrEmpty(ids)) {
			return ajax_error("删除的里程碑ID不能为空");
		}
		String[] id_array = ids.split(Macro.COMMA);
		long[] id_arr = new long[id_array.length];
		for (int i = 0; i < id_arr.length; i++) {
			id_arr[i] = Long.valueOf(id_array[i]);
		}
		milestoneService.remove_milestone_ids(id_arr);
		return ajax_info("删除成功");
	}

	/**
	 * 获取所有项目的id和name，并作为commbo对象返回给commbo使用。
	 *
	 * @return 项目Commbo
	 */
	@RequestMapping("all_project")
	@ResponseBody
	public List<CommboValue> project_commbo() {
		List<Project> projects = projectService.all_projects();
		List<CommboValue> commboValues = Lists.newArrayList();
		CommboValue commboValue;
		for (Project project : projects) {
			commboValue = new CommboValue();
			mapper.map(project, commboValue);
			commboValues.add(commboValue);
		}
		return commboValues;
	}

	/**
	 * 获取某项目所有的团队成员的id和name，并作为commbo对象使用。
	 *
	 * @param p_id
	 * @return
	 */
	@RequestMapping("team_in_project")
	@ResponseBody
	public List<CommboValue> team_in_project_commbo(
			@RequestParam(value = "p_id", required = false) String p_id) {

		List<Account> accounts = projectService.getProjectInformation(
				Long.valueOf(p_id)).getAccounts();
		List<CommboValue> commboValues = new ArrayList<CommboValue>();
		CommboValue commboValue;
		for (Account account : accounts) {
			commboValue = new CommboValue();
			mapper.map(account, commboValue);
			commboValues.add(commboValue);
		}
		return commboValues;
	}

	@InitBinder
	protected void initBinder(HttpServletRequest request,
							  ServletRequestDataBinder binder) throws Exception {
		// 对于需要转换为Date类型的属性，使用DateEditor进行处理
		binder.registerCustomEditor(Date.class, new DateEditor(null));
	}

	/**
	 * 显示milestone的所有反馈信息
	 *
	 * @param criteria     分页信息
	 * @param milestone_id 里程碑的id
	 * @param label        标签，用于表示反馈信息状态
	 * @return
	 */
	@RequestMapping("issue_list.json")
	@ResponseBody
	public PaginationResult<Issue> all_issue_milestone(
			@PaginationParam(required = false) PaginationCriteria criteria,
			@RequestParam(value = "milestone_id", required = false) long milestone_id,
			@RequestParam(value = "label", required = false) String label) {
		Milestone milestone = milestoneService.get_milestone_id(milestone_id);
		return issueService.page_issue_milestone_list(criteria, milestone,
				label);
	}

	/**
	 * 设置里程碑达到
	 *
	 * @param milestone_id 里程碑的id
	 */
	@RequestMapping(value = "set_reach", method = RequestMethod.POST)
	@ResponseBody
	public AjaxMessage set_milestone_reach(
			@RequestParam(value = "id_post", required = false) long milestone_id,
			@RequestParam(value = "content", required = false) String content) {
		milestoneService.set_milestone_reach(content, milestone_id);
		return ajax_info("设置成功！");
	}

	/**
	 * 查询里程碑详细信息包括基本信息和里程碑所包含的问题列表
	 *
	 * @param pid 里程碑所在项目id
	 * @param mid 里程碑id
	 * @author liyasoft
	 * @version 2012/12/26 16:49
	 */
	@RequestMapping("/view/{mid}/{pid}")
	public String milestone_view(@PathVariable long pid,
								 @PathVariable long mid,
								 Model model) {
		Project project = projectService.fromId(pid);
		model.addAttribute("project", project);
		return "project/milestone/view";
	}

	/**
	 * 跳转到issue 列表
	 *
	 * @return issue list界面
	 */
	@RequestMapping(value = "issue_list/{mid}", method = RequestMethod.GET)
	public String p_issue(@PathVariable("mid") long milestone_id, Model model) {
		model.addAttribute("type_json", JsonMapper.nonDefaultMapper().toJson(typeService.all_types()));
		final List<Priopity> priopity_list = priopityService.priopity();
		model.addAttribute("labels", labelService.all_labels());
		model.addAttribute("priopities", priopity_list);
		model.addAttribute("priopities_json", JsonMapper.nonDefaultMapper().toJson(priopity_list));
		Project project = projectService.fromId(milestoneService.get_milestone_id(milestone_id).getProject());
		model.addAttribute("project", project);
		model.addAttribute("milestone_id", milestone_id);
		return "project/issue/list";
	}

    /**
     * 获取里程碑信息
     *
     * @param milestone_id   里程碑id
     * @param model
     * @return 查看里程碑界面
     */
    @RequestMapping(value = "info/{mid}",method = RequestMethod.GET)
    public String milestone_info(@PathVariable(value = "mid") int milestone_id,Model model){
        Milestone milestone = milestoneService.get_milestone_id(milestone_id);
        Project project = projectService.fromId(milestone.getProject());
        model.addAttribute("project",project);
        model.addAttribute("milestone",milestone);
         return "project/milestone/info";
    }
    /**
     * 直接反馈问题，不需要通过登录的方式的保存操作
     *
     * @param attachment
     * @return
     */
    @RequestMapping(value = "issue_import", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMessage issue_import( @RequestParam(value = "attachment", required = false) MultipartFile attachment,Model model) {
              String issue_string= new String();
                try {
                    issue_string = milestoneService.issue_import(attachment);
                    return ajax_info(issue_string);
                } catch (Exception e) {
                    logger.error("文件上传保存时发生错误!", e);
                    return ajax_error("文件上传保存时发生错误!");
                }

    }
}
